<?php

namespace app\model;

use think\facade\Db;
use think\Model;
use think\validate\ValidateRule;

class ProductsModel extends Model {

    protected $table ="products";

    protected $pk = 'product_id';
    private $cacheKey="product:id:";

    //商品基础信息缓存key
    private $baseCacheKey="product:id:base:";
    private $cacheTime=5184000;

    private $redisModel;

    private $productSalesSpecsModel;

    private $shopsModel;


    public function __construct(){

        $this->redisModel = new RedisModel();

        $this->productSalesSpecsModel = new ProductSalesSpecsModel();

        $this->shopsModel = new ShopsModel();

    }


    /*
     * 获取total
     * */
    public function getTotal($where=[]){
        return Db::name('products')->alias("p")
            ->join('base_category c','p.category_id = c.category_id')
            ->join('shops s','p.shop_id = s.shop_id')
            ->where($where)->count();
    }


    /*
     * 获取list
     * $from = 1 前端请求，给商品基础信息
     * $from = 2 后端请求，给商品详细信息
     * */
    public function getList($from = 2,$where=[],$page = null,$limit = null,$orderField = null,$orderType = "ASC",$sortType = ""){

        $obj =   Db::name('products')->alias("p")->field("p.product_id")
            ->join('base_category c','p.category_id = c.category_id')
            ->join('shops s','p.shop_id = s.shop_id')
            ->where($where);

        if(!empty($page) && !empty($limit)){
            $obj = $obj->limit(($page-1) * $limit, $limit);
        }

        if(!empty($orderField) && !empty($orderType)){
            $obj = $obj->order($orderField, $orderType);
        }

        if(!empty($sortType)){
            $obj = $obj->order("product_reviews_num", "desc");
        }

        $list = $obj->select();

        if($list){
            $return = [];
            foreach($list as $item){
                $return[] = $from == 1 ? $this->getBaseInfo($item['product_id'],false) : $this->getInfo($item['product_id']);
            }
            return $return;
        }
        return [];
    }


    //获取基础信息
    public function getBaseInfo($productId = 0,$isGetServiceAftersales = true){
        if(empty($productId)){
            return [];
        }
        $cacheKey = $this->baseCacheKey.$productId;
        $info = $this->redisModel->get($cacheKey);
        if($info){
            $info = json_decode($info,true);
        }else{
            $info = Db::name('products')->find($productId);
            $info['format_product_max_price'] = round( $info['product_max_price'] / 100, 2);
            $info['format_product_min_price'] = round( $info['product_min_price'] / 100, 2);
            $info['product_pics'] = !empty($info['product_pics']) ? json_decode($info['product_pics'],true) : "";
            $info['product_description'] = !empty($info['product_description']) ? json_decode($info['product_description'],true) : "";
            $this->redisModel->set($cacheKey,json_encode($info,256),$this->cacheTime);
        }

        $info["product_status"] = $this->getProductStatus($productId);
        $specData = $this->productSalesSpecsModel->getPorductSaleNumAndStock($productId);
        $info['product_sales_num'] = intval($specData['total_sales_num'] ?? 0);
        $info['product_stock'] = intval($specData['total_stock'] ?? 0);
        $info["shop_info"] = $this->shopsModel->getInfo($info["shop_id"],false);
        $isGetServiceAftersales && $info['service_aftersales'] = (new ProductAftersales())->getProductAftersalesList($productId);
        return $info;
    }


    /*
   * 获取订单状态详情
   * */
    public function getInfo($productId){
        $cacheKey = $this->cacheKey.$productId;
        $info = $this->redisModel->get($cacheKey);
        if($info){
            $info =  json_decode($info,true);
        }else{
            $info = Db::name('products')->find($productId);
            $info['format_product_max_price'] = round( $info['product_max_price'] / 100, 2);
            $info['format_product_min_price'] = round( $info['product_min_price'] / 100, 2);
            $info['product_pics'] = !empty($info['product_pics']) ? json_decode($info['product_pics'],true) : null;
            $info['product_description'] = !empty($info['product_description']) ? json_decode($info['product_description'],true) : null;
            $this->redisModel->set($cacheKey,json_encode($info,256),$this->cacheTime);
        }
        if($info){
            $productSalesSpecsModel = new ProductSalesSpecsModel();
            $info["product_status"] = $this->getProductStatus($productId);

            // 关联销售规格数据（避免多次查询，一次搞定）
            $specData = $this->productSalesSpecsModel->getPorductSaleNumAndStock($productId);
            $info['product_sales_num'] = intval($specData['total_sales_num'] ?? 0);
            $info['product_stock'] = intval($specData['total_stock'] ?? 0);

            $info["shop_info"] = $this->shopsModel->getInfo($info["shop_id"],false);
            $info["shop_info"]['shop_status'] = $this->shopsModel->getShopStatus($info["shop_id"]);
            $info["product_status_info"] = (new BaseProductStatusModel())->getInfo($info["product_status"]);
            $info['service_aftersales'] = (new ProductAftersales())->getProductAftersalesList($productId);
            $info['service_return'] = (new ProductReturnCategory())->getProductReturnCategory($productId);
            $info['service_shipping'] = (new ProductShipping())->getProductShipping($productId);
            $info['service_timelines'] = (new ProductTimelines())->getProductTimeline($productId);
            $info['sales_specs_list'] = $productSalesSpecsModel->getProductSalesSpecsList($productId);
            $info['service_attribute'] = (new ProductAttributesModel())->getProductAttributes($productId);
            $info['service_information'] = (new ProductInformationModel())->getProductInformation($productId);
        }

        return $info;
    }


    /*
  * 获取规格状态
  * */
    public function getProductStatus($id){
        if(empty($id) ){
            return false;
        }
        $where=[];
        $where[] = ["product_id","=",$id];
        return Db::name('products')->where($where)->value("product_status");
    }

    /*
  * 获取商品总量
  *
  * */
    public function getShopProductNum($shop_id){
        $where=[];
        $where[] = ['p.is_delete',"=",0];
        $where[] = ['p.product_status','=',1];
        $where[] = ['category_status','=',1];
        $where[] = ['shop_status','=',1];
        $where[] = ['p.shop_id','=',$shop_id];
        return $this->getTotal($where);
    }



    /*
     * 猜你喜欢
     * */
    public function getGuessYouLike($product_id = 0,$limit = 4){

        $productInfo = $this->getBaseInfo($product_id);
        if(!empty($productInfo)){
            $category_id = $productInfo['category_id'];
        }

        $where=[];
        if(!empty($product_id)){
            $where[] = ['p.product_id','<>',$product_id];
        }

        $where[] = ['p.product_status','=',1];
        $where[] = ['category_status','=',1];
        $where[] = ['shop_status','=',1];
        $where[] = ['s.is_delete','=',0];
        $where[] = ['p.is_delete','=',0];
        if(!empty($category_id)){
            $where[] = ['p.category_id','=',$category_id];
        }

        //穿透Db缓存
        $list = Db::name('products')->alias("p")->field("p.product_id")
            ->join('base_category c','p.category_id = c.category_id')
            ->join('shops s','p.shop_id = s.shop_id')
            ->where($where)->orderRaw("RAND()")->limit($limit)->select();
        if($list){
            $return = [];
            foreach($list as $item){
                $return[] = $this->getBaseInfo($item['product_id']);
            }
            return $return;
        }
        return [];
    }

    /*
 * 更新规格销售
 * */
    public function incrProductSalesNum($product_id,$num){
        $where =[];
        $where['product_id'] = $product_id;
        return Db::name('products')->where($where)->inc("product_sales_num",$num)->update();
    }



    /*
     * 购物车增加指定商品的数量
     * */
    public function incrProductViewNum($product_id,$num = 1){
        if(empty($product_id) ){
            return false;
        }

        $where =[];
        $where['product_id'] = $product_id;
        return Db::name('products')->where($where)->inc("product_view_num",$num)->update();
    }



    /*
 * 更新规格销售
 * */
    public function incrProductReviewsNum($product_id,$num){
        $where =[];
        $where['product_id'] = $product_id;
        return Db::name('products')->where($where)->inc("product_reviews_num",$num)->update();
    }

    /*
* 更新操作
* */
    public function updateAll($where,$data){
        return Db::name('products')->where($where)->update($data);
    }
}